<template>

	<view class="scrollConter">
		<view class="bar">
			<statusTab @checkTab="checkTabClick" ref="statusTabRef" :list="list1" />
		</view>
		<view class="conterRow" v-if="listData.length == 0 && !isLoading" style="background: #fff;">
			<view class="nullData">
				<image src="https://img.zhizhuangtong.com/project_media/img/xcx/null.png" mode=""></image>
				<text>暂无数据</text>
			</view>
		</view>

		<view class="conterRow" v-else>
			<view class="cards" v-for="(item,index) in listData" :key="index">
				<view class="label">
					<!-- <text v-for="(item1s,index1s) in item.cat" :key="index1s">{{item1s.name}}</text> -->
					<text v-if="item.cat[0].name">{{item.cat[0].name}}</text>
					<text>-</text>
					<text v-if="item.cat[1].name">{{item.cat[1].name}}</text>

				</view>

				<view class="title" v-if="item.code">
					<text class="lb">
						需求编码：
					</text>
					<text class="text">{{item.code}}</text>
				</view>
				<view class="title" v-if="item.create_time">
					<text class="lb">
						发布时间：
					</text>

					<text class="text">{{item.create_time}}</text>
				</view>
				<view class="title" v-if="item.service_time">
					<text class="lb">
						服务时间：
					</text>
					<text class="text">{{item.service_time}}</text>
				</view>
				<view class="title">
					<text class="lb">
						所在地区：
					</text>
					<view class="city">
						<text class="text2" v-if="item.province_name">{{item.province_name}}</text>
						<text class="text2" v-if="item.city_name">{{item.city_name}}</text>
						<text class="text2" v-if="item.county_name">{{item.county_name}}</text>
						<text class="text2" v-if="item.address">{{item.address}}</text>
					</view>
				</view>

				<view class="title">
					<text class="lb">备注：</text>
					<text class="text">{{item.desc}}</text>
				</view>
				<view class="tips type1" v-if="item.order">
					需支付{{item.order?.type_text}}：¥{{item.order?.money}}
				</view>

				<!-- <view class="tips type2" v-if="checkStatus == 1">
					设计师正在为您设计方案中...
				</view> -->
				<view class="btn">
					<view @click="pay(item.order.id)" v-if="item.order && !item.isExpired">付款</view>

					<view @click="onDetails(item.id)">详情</view>

					<view @click="editDeam(item.id)" v-if="item.status == 1">编辑</view>

					<view @click="preview(item.project.plan_enid)"
						v-if="item.status == 4 && item.project.design_status ==3">设计预览
					</view>
					<view @click="acceptancePost(item)" v-if="item.status == 4 && item.project.design_status ==3">
						设计验收
					</view>
					<view @click="constructionAcceptance(item.project.demand_id)"
						v-if="item.status == 4 && item.project.build_status ==3">施工验收
					</view>

					<view @click="offDeam(item.id)" v-if="item.status == 1 ||item.status == 2||item.status == 3">关闭
					</view>
					<!-- <view @click="communication">沟通</view> -->
				</view>
			</view>

		</view>
		<view v-if="isLoading" class="load-more-box">
			<text>加载中...</text>
		</view>

		<view v-if="listData.length !== 0 && !isLoading && !hasMoreData" class="load-more-box">
			<text>已经到底了</text>
		</view>
	</view>


	<up-popup :show="showTel" :round="10" mode="bottom" @close="showTel = false" @open="showTel = true">
		<bindTel @closeModel='showTel=false' />
	</up-popup>




</template>

<script setup>
	import bindTel from '../../../components/bindTel.vue'

	import {
		list,
		demand_close
	} from '@/api/require.js';
	import {
		ref,
		onMounted,
		defineExpose,
		watch
	} from 'vue';
	import {
		onLoad,
		onReady,
		onShow,
		onHide,
		onShareAppMessage,
		onShareTimeline,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import env from '@/api/config.js';
	import statusTab from '../../../components/statusTab/index.vue'

	const active = ref('')

	const statusTabRef = ref(null)

	const params = ref({
		status: '',
		page: 1,
		page_size: 10
	})
	const listData = ref([]) //列表数据

	// tabs数据
	const list1 = ref([{
			name: '待接单',
		},

		{
			name: '服务中',

		},
		{
			name: '待验收',

		},
		{
			name: '已结束',

		}
	])

	const showTel = ref(false)
	const showGetTel = ref(false)

	const type = ref('')
	onLoad((option) => {
		listData.value = []
		params.value.status = '1,2'
		params.value.page = 1

		if (option.status) {
			type.value = option.status;
			// 待接单
			if (type.value == 0) {
				params.value.status = '1,2'
				// console.log('待接单')
				checkStatus.value = 1
			} else if (type.value == 1) {
				// 服务中
				params.value.status = '3'
				// console.log('服务中')
				checkStatus.value = 2
			} else if (type.value == 2) {
				// 待验收
				params.value.status = '4'
				checkStatus.value = 3
				// console.log('待验收')
			} else {
				// 已结束
				params.value.status = '5,6'
				// console.log('已结束')
				checkStatus.value = 4
			}


		}
	})
	onReady(() => {
		if (statusTabRef.value) {
			statusTabRef.value.active = type.value
		}
	})


	onShow(() => {
		uni.$on('refreshIfNeeded', function(dat) {
			if (dat) {
				// params.value.status = '1';
				params.value.page = 1;
				listData.value = []
				queryDemandList()
			}
			uni.$off('refreshIfNeeded')
		})
	})

	onMounted(() => {
		queryDemandList()
	});

	onReachBottom(() => {
		queryDemandList()

	});



	const checkTabClick = (val) => {
		checkStatus.value = val
		if (checkStatus.value == 0) {
			params.value.status = '1,2'
		} else if (checkStatus.value == 1) {
			params.value.status = '3'
		} else if (checkStatus.value == 2) {
			params.value.status = '4'
		} else {
			params.value.status = '5,6'
		}
		params.value.page = 1
		listData.value = []
		queryDemandList()
	}

	// 数据列表、加载状态和分页参数
	const hasMoreData = ref(true); // 初始化为true，表示还有更多数据
	const isLoading = ref(false); // 加载状态

	// 需求列表
	const queryDemandList = async () => {
		isLoading.value = true; // 设置加载中
		try {
			const res = await list(params.value);
			if (res.code === 1) {
				// listData.value = res.data.list

				// if (params.value.page === 1) {
				// 	listData.value = res.data.list;
				// } else {
				// 	listData.value.push(...res.data.list);
				// }

				if (params.value.page === 1) {
					listData.value = res.data.list.map(item => ({
						...item,
						isExpired: item.order ? checkIfExpired(item.order.auto_cancel) : false
					}));
				} else {
					// 如果不是第一页，添加到现有 listData 中
					listData.value.push(...res.data.list.map(item => ({
						...item,
						isExpired: item.order ? checkIfExpired(item.order.auto_cancel) : false
					})));
				}


				// 判断是否还有更多数据
				if (res.data.list.length < params.value.page_size) {
					hasMoreData.value = false; // 没有更多数据
				} else {
					hasMoreData.value = true; // 还有更多数据
				}
				params.value.page += 1; // 页码递增
			}
			setTimeout(() => {
				isLoading.value = false;
			}, 500);
		} catch (error) {
			console.error('请求数据失败:', error);
		} finally {
			isLoading.value = false; // 加载完成

		}
	}


	// 判断是否超过截止时间
	const checkIfExpired = (autoCancelTime) => {
		const currentTime = new Date();
		const cancelTime = new Date(autoCancelTime);

		// 转换为 UTC 时间戳来进行比较
		const currentTimestamp = currentTime.getTime(); // 当前时间的时间戳（毫秒）
		const cancelTimestamp = cancelTime.getTime(); // 截止时间的时间戳（毫秒）

		console.log('autoCancelTime', autoCancelTime);
		console.log('当前时间', currentTime);
		console.log('截止时间', cancelTime);

		return currentTimestamp > cancelTimestamp;
	};




	// 去付款
	const pay = async (id) => {
		// 绑定手机号
		// 绑定手机号
		if (uni.getStorageSync('useInfo').allin_mobile == 0) {
			showTel.value = true
			console.log('绑定手机')
		} else {
			console.log('去付款')
			// 去付款
			const orderItem = listData.value.find(item => item.order.id === id);
			if (!orderItem || (orderItem.order && checkIfExpired(orderItem.order.auto_cancel))) {
				uni.showToast({
					title: '订单已过期，无法付款',
					icon: 'none'
				});
				return;
			}
			uni.navigateTo({
				url: '/pages/common/pay/index?id=' + id
			});
		}
	}

	// 已关联设计方案 预览 5
	const preview = async (id) => {
		const apiUrl = env.config;
		let domain = '';
		if (apiUrl.includes('-service')) {
			// 测试
			domain = 'dev-design.zhizhuangtong.com'; // dev 环境
		} else {
			// 正式环境
			domain = 'pre-design.zhizhuangtong.com'; // 正式环境
		}

		const url = `https://${domain}/#/share/${id}`;
		console.log(url);
		// const url = 'https://dev-design.zhizhuangtong.com/#/share/' + id
		// console.log('urlurlurl',url)
		uni.navigateTo({
			url: '/pages/webView/index?url=' + encodeURIComponent(url)
		});
	}

	// 设计验收  6
	const acceptancePost = async (data) => {
		const cat = data.cat[0]?.id
		uni.navigateTo({
			url: '/pages/demand/constructionAcceptance/index2?id=' + data.id + '&check=' + data.check+ '&cat=' + cat
		});
	}


	// 施工验收  9
	const constructionAcceptance = async (id) => {
		uni.navigateTo({
			url: `/pages/demand/constructionAcceptance/index?id=${id}&type=1`
			
		});
	}




	const show = ref(false);

	const checkStatus = ref(0)
	// 需求详情
	const onDetails = (id) => {
		// wx.showToast({
		// 	title: '需求详情正在开发中！',
		// 	icon: 'none',
		// 	duration: 2000
		// });
		uni.navigateTo({
			url: '/pages/demand/demandStatusDetails/index?id=' + id
		});
	}

	// 编辑需求
	const editDeam = (id) => {
		uni.redirectTo({
			url: '/pages/demand/editDemandStatus/index?id=' + id
		});

		// wx.showToast({
		// 	title: '编辑需求正在开发中！',
		// 	icon: 'none',
		// 	duration: 2000
		// });
	}

	// 关闭需求
	const offDeam = async (id) => {

		const res = await demand_close({
			id: id
		});
		if (res.code === 1) {
			console.log('关闭序曲', res.data)
			wx.showToast({
				title: '关闭需求成功！',
				icon: 'none',
				icon: 'success',
				duration: 1000
			});
			// queryDemandList()
			// listData.value = res.data.list
		} else {
			wx.showToast({
				title: res.data.msg,
				icon: 'none',
				icon: 'error',
				duration: 1000
			});

		}
		params.value.page = 1;
		queryDemandList()
	}

	// 沟通需求
	const communication = () => {
		wx.showToast({
			title: '沟通需求正在开发中！',
			icon: 'none',
			duration: 2000
		});
	}
	
	// 需求付款
	const payDeam = () => {
		wx.showToast({
			title: '需求付款正在开发中！',
			icon: 'none',
			duration: 2000
		});
	}

	// 验收需求
	const acceptanceDeam = () => {
		wx.showToast({
			title: '验收需求正在开发中！',
			icon: 'none',
			duration: 2000
		});
	}
</script>

<style lang="less" scoped>
	.tabs {
		width: 100%;
		height: 100%;
		background-color: #fff;
		display: flex;
		justify-content: space-around;
	}

	.scrollConter {
		width: 100%;
		min-height: 100vh;
		box-sizing: border-box;
		background-color: #f2f2f2;
		display: flex;
		align-content: flex-start;
		flex-wrap: wrap;

		.bar {
			height: 80rpx;
			width: 100%;
		}

		.conterRow {
			width: 100%;
			height: calc(100% - 80rpx);
			padding: 20rpx 20rpx 0;
			box-sizing: border-box;

			.cards {
				width: 100%;
				background: #FFFFFF;
				border-radius: 18rpx;
				padding: 30rpx 30rpx 0;
				margin-bottom: 20rpx;
				box-sizing: border-box;

				&:last-child {
					margin-bottom: 0;
				}

				.label {
					display: flex;
					width: 100%;
					height: 100%;
					margin-bottom: 20rpx;

					text {
						margin-right: 10rpx;
						display: flex;
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: 500;
						font-size: 28rpx;
						height: 30rpx;
						color: #333333;
						line-height: 30rpx;
						text-align: left;
						font-style: normal;
						text-transform: none;
					}
				}

				.tips {
					width: 100%;

					border-radius: 6rpx 6rpx 6rpx 6rpx;
					display: flex;
					align-items: center;
					padding: 10rpx;

					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					text-align: left;
					font-style: normal;
					text-transform: none;
					margin-bottom: 25rpx;

				}

				.type1 {
					background: #FFF6F6;
					color: #FF4C4C;
				}

				.type2 {
					background: #FFF8F4;
					color: #FF7F3A;
				}

				.title {
					margin-bottom: 15rpx;
					display: flex;
					flex-wrap: wrap;
					align-items: flex-start;

					.lb {
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 26rpx;
						color: #666666;
						line-height: 36rpx;
						text-align: left;
						font-style: normal;
						text-transform: none;
						width: 150rpx;
						height: 100%;
						display: flex;
						align-items: flex-start;
					}

					.city {
						display: flex;
						text-align: left;
						flex: 1;
						flex-wrap: wrap;

						.text2 {
							display: flex;
							padding: 0 10rpx;
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 26rpx;
							color: #999999;
							line-height: 36rpx;
							text-align: left;
							text-transform: none;
							height: 100%;
							display: flex;
							align-items: flex-start;
							word-break: break-all;
						}
					}

					.text {
						padding: 0 10rpx;
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 26rpx;
						color: #999999;
						line-height: 36rpx;
						text-align: left;
						text-transform: none;
						flex: 1;
						height: 100%;
						display: flex;
						align-items: flex-start;
						word-break: break-all;
					}


				}

				.btn {
					display: flex;
					align-items: center;
					justify-content: flex-end;
					padding: 25rpx 0 30rpx;

					view {
						width: 127rpx;
						height: 55rpx;
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #333333;
						line-height: 55rpx;
						text-align: center;
						font-style: normal;
						text-transform: none;
						background: #FDFDFD;
						border-radius: 8rpx;
						border: 1rpx solid #D2D2D2 !important;
						margin-left: 20rpx;

						&:first-child {
							margin-left: 0;
						}
					}
				}
			}
		}


		.load-more-box {
			text-align: center;
			width: 100%;
			padding-top: 20rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
			color: #7A7A7A;
		}

	}
</style>